import pandas as pd
import os

def generate_brain_parameters(output_dir):
    """
    生成脑参数相关的多个表格并保存为CSV。
    output_dir: 输出文件夹路径。
    """
    os.makedirs(output_dir, exist_ok=True)

    # 1. CSF Flow
    df_csf_flow = pd.DataFrame([
        ["CSF production rate (L/h)", 0.021, 10],
        ["Bulk flow from ISF to CSF (% CSF Production)", 25, 8],
        ["CSF spinal absorption rate (% CSF production rate)", 38, 30],
        ["Bulk flow from spinal CSF to cranial CSF (% CSF spinal absorption rate)", 90, 100],
    ], columns=["Parameter", "Mean", "CV (%)"])
    df_csf_flow.to_csv(os.path.join(output_dir, "csf_flow.csv"), index=False)

    # 2. Volume
    df_volume = pd.DataFrame([
        ["ICF (% Brain Mass)", 80, 5],
        ["Brain Endothelial Space (% of Brain Volume)", 0.5, 0],
    ], columns=["Parameter", "Mean", "CV (%)"])
    df_volume.to_csv(os.path.join(output_dir, "brain_volume.csv"), index=False)

    # 3. User Defined
    df_user = pd.DataFrame([
        ["CV(%)", 8.7, 11.9],
        ["CSF (% Brain volume)", 10.5, 9.2],
        ["Spinal (% CSF)", 20, 20],
        ["Intracranial blood volume (% Brain volume)", 5, 5],
    ], columns=["Parameter", "Mean", "CV (%)"])
    df_user.to_csv(os.path.join(output_dir, "brain_user_defined.csv"), index=False)

    # 4. Brain Transporter Absolute Abundances
    df_transporter = pd.DataFrame([
        ["Brain capillary protein (mg brain capillary protein/g brain)", 2.33, 47],
    ], columns=["Parameter", "Mean", "CV (%)"])
    df_transporter.to_csv(os.path.join(output_dir, "brain_transporter_abundance.csv"), index=False)

    # 5. Neural Compartment ISF-ICF Barrier Tissue Protein Scalars
    df_neural = pd.DataFrame([
        ["Brain neural parenchymal protein (mg/g ICF Neural Tissue)", 76.29, 43],
        ["Brain neuronal protein (mg/g ICF Neural Tissue)", 56.57, 43],
        ["Brain glial protein (mg/g ICF Neural Tissue)", 19.72, 43],
    ], columns=["Parameter", "Mean", "CV (%)"])
    df_neural.to_csv(os.path.join(output_dir, "brain_neural_protein_scalars.csv"), index=False)

    # 6. Brain Transporter Absolute Abundance (详细)
    df_transporter_detail = pd.DataFrame([
        ["ABCB1 (MDR1)", 3.25, 1, 56, 0, 0, 0, 0, 0, 0],
        ["ABCC4 (MRP4)", 0.24, 1, 44, 0, 0, 0, 0, 0, 0],
        ["ABCG2 (BCRP)", 5.59, 1, 65, 0, 0, 0, 0, 0, 0],
        ["ISF (BBB) Efflux (Brain)", 0, 1, 60, 0, 0, 0, 0, 0, 0],
        ["SLC2A1 (GLUT1)", 60.07, 1, 70, 0, 0, 0, 0, 0, 0],
        ["SLC29A1 (ENT1)", 0.62, 1, 71, 0, 0, 0, 0, 0, 0],
        ["SLC16A1 (MCT1)", 4.75, 1, 69, 0, 0, 0, 0, 0, 0],
        ["SLCO1A2 (OATP1A2)", 0.54, 1, 19, 0, 0, 0, 0, 0, 0],
        ["SLCO1B3 (OATP1B3)", 0.46, 1, 33, 0, 0, 0, 0, 0, 0],
        ["SLCO1C1 (OATP1C1)", 0.27, 1, 11, 0, 0, 0, 0, 0, 0],
        ["SLCO2B1 (OATP2B1)", 0.41, 1, 58, 0, 0, 0, 0, 0, 0],
        ["SLC22A1 (OCT1)", 0.56, 1, 16, 0, 0, 0, 0, 0, 0],
        ["SLC22A3 (OCT3)", 0.62, 1, 13, 0, 0, 0, 0, 0, 0],
        ["SLC22A6 (OAT1)", 0.48, 1, 23, 0, 0, 0, 0, 0, 0],
        ["SLC22A7 (OAT2)", 7.9, 1, 48, 0, 0, 0, 0, 0, 0],
        ["SLC22A8 (OAT3)", 0.27, 1, 11, 0, 0, 0, 0, 0, 0],
        ["SLC22A9 (OAT7)", 0.51, 1, 20, 0, 0, 0, 0, 0, 0],
        ["ISF (BBB) Uptake (Brain)", 0, 1, 60, 0, 0, 0, 0, 0, 0],
    ], columns=["Transporter","Absolute Abundance (pmol/mg brain capillary protein)","ET Mean","CV (%)","PT Mean","CV PT (%)","IT Mean","CV IT (%)","UT Mean","CV UT (%)"])
    df_transporter_detail.to_csv(os.path.join(output_dir, "brain_transporter_abundance_detail.csv"), index=False)

    # 7. Brain Transporter Kinetics
    df_kinetics = pd.DataFrame([
        ["Molecular Weight (Da)", 95000, None],
        ["Rmax (uM)", 3.3, 30],
        ["Kdeg (1/h)", 0.0625, 30],
        ["Ksyn (uM/h)", 0.20625, None],
    ], columns=["Parameter","Mean","CV (%)"])
    df_kinetics.to_csv(os.path.join(output_dir, "brain_transporter_kinetics.csv"), index=False)

    # 8. cCSF (BCSFB) Transporter Abundance
    df_ccsf = pd.DataFrame([
        ["cCSF (BCSFB) Efflux (Brain)", 0, 1, 30, 0, 0, 0, 0, 0, 0],
        ["cCSF (BCSFB) Uptake (Brain)", 0, 2, 30, 0, 0, 0, 0, 0, 0],
    ], columns=["Transporter","ET Mean","ET Mean (Abundance)","ET CV (%)","PT Mean","PT CV (%)","IT Mean","IT CV (%)","UT Mean","UT CV (%)"])
    df_ccsf.to_csv(os.path.join(output_dir, "brain_ccsf_transporter_abundance.csv"), index=False)

    # 9. ICF Transporter Abundance
    df_icf = pd.DataFrame([
        ["ICF Efflux（Brain）", 0, 1, 30, 0, 0, 0, 0, 0, 0],
        ["ICF Uptake（Brain）", 0, 2, 30, 0, 0, 0, 0, 0, 0],
    ], columns=["Transporter","ET Mean","ET Mean (Abundance)","ET CV (%)","PT Mean","PT CV (%)","IT Mean","IT CV (%)","UT Mean","UT CV (%)"])
    df_icf.to_csv(os.path.join(output_dir, "brain_icf_transporter_abundance.csv"), index=False)

    print(f"所有脑参数表格已保存到: {output_dir}")


def generate_brain_parameters_from_df(df):
    """
    批量生成脑参数，输入人口学DataFrame，输出带id的脑参数DataFrame。
    参数均采用原脚本中的均值，不做任何数据内容修改。
    """
    results = []
    for idx, row in df.iterrows():
        person_id = row.get('id', idx)
        # 主要参数均用原脚本均值
        csf_prod = 0.021
        csf_absorp = 38
        brain_icf = 80
        brain_endoth = 0.5
        brain_cap_protein = 2.33
        results.append({
            'id': person_id,
            'Brain_csf_production_rate_L_h': csf_prod,
            'Brain_csf_spinal_absorption_rate_percent': csf_absorp,
            'Brain_icf_percent_brain_mass': brain_icf,
            'Brain_endothelial_space_percent_brain_volume': brain_endoth,
            'Brain_capillary_protein_mg_per_g': brain_cap_protein
        })
    return pd.DataFrame(results)


def main():
    output_dir = os.path.dirname(os.path.abspath(__file__))
    generate_brain_parameters(output_dir)

if __name__ == "__main__":
    import pandas as pd
    # 构造测试数据
    test_df = pd.DataFrame({
        'id': [1, 2],
        'age': [30, 40],
        'bsa': [1.7, 1.8]
    })
    result = generate_brain_parameters_from_df(test_df)
    print(result) 